<template>
  <div>
    <el-upload
      list-type="picture-card"
      action="#"
      :on-preview="previewFn"
      :limit="1"
      :file-list="fileList"
      :class="{ disable: fileComputed }"
      :on-remove="removeFn"
      :on-change="changeFn"
      :before-upload="beforeUploadFn"
      :http-request="uploadFn"
    >
      <i class="el-icon-plus avatar-uploader-icon" />
    </el-upload>
    <el-progress v-if="isShow" :percentage="percent" style="width: 180px" />

    <!-- 对话框 -->
    <el-dialog title="预览图片" :visible.sync="dialogTableVisible">
      <img :src="imgUrl" alt="" style="width: 100%">
    </el-dialog>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5' // 引入腾讯云 sdk
const cos = new COS({ // 实例化上传 sdk
  SecretId: 'AKIDUs31lGXZNxQjqiLjtoUwBG9oEQN6aooZ', // 身份识别 ID
  SecretKey: 'aw3va2IJLAk6D5i6F9pGSO8ex2sTpxqU' // 身份密钥
})
export default {
  data() {
    return {
      imgUrl: '',
      baseUid: null, // 上传前检测的uid
      dialogTableVisible: false, // 对话框显示隐藏
      fileList: [], // 放图片的数组
      percent: 0, // 进度条
      isShow: false // 进度条显示隐藏
    }
  },
  computed: { // 计算属性
    fileComputed() {
      return this.fileList.length === 1 && this.fileList
    }
  },
  methods: { // 方法
    previewFn(file) { // 点击图片列表的钩子
      this.dialogTableVisible = true
      this.imgUrl = file.url
    },
    removeFn(file, fileList) { // 删除图片的钩子
      // 排除法实现
      this.fileList = this.fileList.filter(item => item.uid !== file.uid)
      //   this.fileList = fileList
    },
    changeFn(file, fileList) { // 文件上传的钩子
      this.fileList = fileList
    },
    beforeUploadFn(file) { // 文件上传前钩子
      const imgType = ['image/jpeg', 'image/png', 'image/gif', 'image/bmp']
      if (!imgType.includes(file.type)) {
        this.$message.error('上传图片的格式只能是 JPG,PNG,GIF,BMP')
        return false
      }
      // 检测图片大小5M  1M => 1024KB => 1024B
      const Maxsize = file.size / 1024 / 1024 < 5
      if (!Maxsize) {
        this.$message.error('上传头像图片大小不能超过 5MB!')
        return false
      }
      this.isShow = true
      this.baseUid = file.uid
      return true
    },
    uploadFn(params) {
      if (params.file) {
        // 执行上传操作
        cos.putObject({
          Bucket: 'kutongxue-1301834465', /* 填入您自己的存储桶，必须字段 */
          Region: 'ap-nanjing', /* 存储桶所在地域，例如ap-beijing，必须字段 */
          Key: params.file.name, /* 文件名 */
          StorageClass: 'STANDARD',
          Body: params.file, // 上传文件对象
          onProgress: (params) => { // 进度条的回调函数
            this.percent = params.percent * 100
          }
        }, (err, data) => {
          if (!err && data.statusCode === 200) {
            this.fileList = this.fileList.map(item => {
              if (item.uid === this.baseUid) {
                return { url: 'http://' + data.Location, upload: true }
              } else {
                return item
              }
            })
          }
          // 重置百分比
          setTimeout(() => {
            this.isShow = false
            this.percent = 0
          }, 2000)
        })
      }
    }
  }
}
</script>

<style>
.disable .el-upload--picture-card {
  display: none;
}
</style>
